  {  Petrova Tatjana
     2012/10/29
     This program writes the sum of  polynomials .}
program polynomials;

{$APPTYPE CONSOLE}

uses
  SysUtils;
type
  pelement=^element;
  element=record
    value:integer;
    value2:integer;
    next:pelement;
  end;
procedure AddToBegin(var head:pelement;num,num1:integer);
var
  tmp : pelement;
begin
  tmp := head;
  new(head);
  head^.value := num;
  head^.value2 := num1;
  head^.next := tmp;
end;

procedure AddToEnd (var head:pelement;
                        num,num1 : integer);
var
  current : pelement;
begin
  if(head<>nil) then
  begin
    current:=head;
    while(current^.next<>nil)do
      current := current^.next;
    new(current^.next);
    current^.next^.value:=num;
    current^.next^.value2:=num1;
    current^.next^.next:=nil
  end else
    AddToBegin(head,num,num1);
  end;

procedure printList (head : pelement);
var
  current : pelement;
begin
  current := head;
  while(current<>nil) do
  begin
    writeln(current^.value,' ',current^.value2);
    current := current^.next;
  end;
end;


procedure  SumOfPolynomials (var head,head1:pelement);
var
  N,N1,i,c,d:integer;
  fin:textFile;
  current,current1,tmp:pelement;
begin
  assignFile(fin,'input.txt');
  reset(fin);
  readln(fin,N);
  for i:=1 to N do
  begin
    readln(fin,c,d);
    AddToEnd(head,c,d);
  end;
  readln(fin,N1);
  for i:=1 to N1 do
  begin
    readln(fin,c,d);
    AddToEnd(head1,c,d);
  end;
  if (N>N1) then
  begin
    current1:=head;
    current:=head1
  end else
  begin
    current:=head;
    current1:=head1;
  end;
  while(current<>nil) do
  begin
    if (current.value2=current1.value2) then
      current1.value := current1.value+current.value
    else
    begin
      AddToBegin(current1,current.value,current.value2);
    end;
    current := current^.next;
    current1 := current1^.next;
  end;
  printlist(current1);
  closefile(fin);
end;
procedure  ProductOfPolynomials (var head,head1:pelement);
var
  N,N1,i,c,j,d:integer;
  fin:textFile;
  current,current1,tmp:pelement;
begin
  assignFile(fin,'input.txt');
  reset(fin);
  readln(fin,N);
  for i:=1 to N do
  begin
    readln(fin,c,d);
    AddToEnd(head,c,d);
  end;
  readln(fin,N1);
  for i:=1 to N1 do
  begin
    readln(fin,c,d);
    AddToEnd(head1,c,d);
  end;
  current:=head;
  current1:=head1;
  for i:=1 to N do
  begin
    for j:=1 to N1 do
    begin
      current^.value2:= current^.value2+current1^.value2 ;
      current1:=current1^.next;
    end;
    current:=current^.next;
  end;
  printList (current);
end;

var
  head,head1:pelement;


begin
  SumOfPolynomials(head,head1);
  readln;
end.



